All files / src/app/api/admin/segments/[id] route.ts

0% Statements 0/209
100% Branches 0/0
0% Functions 0/1
0% Lines 0/209

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210                                                                                                                                                                                                                                                                                                                                                                                                                                   
export const dynamic = "force-dynamic";

import { NextRequest, NextResponse } from 'next/server';
import { } from "next-auth";
import { prisma } from "@/lib/prisma";
import { logger } from "@/lib/logging";
import { z } from "zod";
import {
  withAdmin,
  withErrorHandling,
  successResponse,
  ApiError,
  ApiSuccessResponse,
  ApiErrorResponse } from "@/lib/api";
import { RouteContext } from "@/lib/api/middleware";

const segmentUpdateSchema = z.object({
  name: z.string().min(1).max(100).optional(),
  description: z.string().max(500).optional().nullable(),
  rules: z
    .array(
      z.object({
        conditions: z.array(
          z.object({
            field: z.string(),
            operator: z.string(),
            value: z.union([
              z.string(),
              z.number(),
              z.array(z.string()),
              z.array(z.number()),
            ]) })
        ),
        logic: z.enum(["AND", "OR"]).default("AND") })
    )
    .optional(),
  isActive: z.boolean().optional() });

interface RouteParams {
  params: Promise<{ id: string }>;
}

/**
 * GET /api/admin/segments/[id]
 * Get a single segment with details
 */
async function handleGet(_request: NextRequest,
  context: RouteContext | undefined): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const { id } = await (context as RouteParams).params;
  const segmentId = parseInt(id);

  if (isNaN(segmentId)) {
    throw ApiError.badRequest("Invalid segment ID");
  }

  const segment = await prisma.customerSegment.findUnique({
    where: { id: segmentId },
    include: {
      promotions: {
        include: {
          promotion: {
            select: {
              id: true,
              name: true,
              displayName: true,
              isActive: true } } } } } });

  if (!segment) {
    throw ApiError.notFound("Segment");
  }

  // Calculate member count
  const memberCount = await calculateSegmentMemberCount(segment.rules);

  // Get sample members
  const sampleMembers = await getSampleMembers(segment.rules, 5);

  return successResponse({
    id: segment.id,
    name: segment.name,
    description: segment.description,
    rules: segment.rules,
    isActive: segment.isActive,
    memberCount,
    sampleMembers,
    promotions: segment.promotions.map((p) => p.promotion),
    createdAt: segment.createdAt,
    updatedAt: segment.updatedAt });
}

/**
 * PUT /api/admin/segments/[id]
 * Update a segment
 */
async function handlePut(request: NextRequest,
  context: RouteContext | undefined): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const { id } = await (context as RouteParams).params;
  const segmentId = parseInt(id);

  if (isNaN(segmentId)) {
    throw ApiError.badRequest("Invalid segment ID");
  }

  const body = await request.json();

  // Validate input
  const validationResult = segmentUpdateSchema.safeParse(body);
  if (!validationResult.success) {
    throw ApiError.validation("Validation failed", validationResult.error.issues);
  }

  const validatedData = validationResult.data;

  const existing = await prisma.customerSegment.findUnique({
    where: { id: segmentId } });

  if (!existing) {
    throw ApiError.notFound("Segment");
  }

  const segment = await prisma.customerSegment.update({
    where: { id: segmentId },
    data: {
      ...(validatedData.name && { name: validatedData.name }),
      ...(validatedData.description !== undefined && {
        description: validatedData.description }),
      ...(validatedData.rules && { rules: validatedData.rules }),
      ...(validatedData.isActive !== undefined && {
        isActive: validatedData.isActive }) } });

  const memberCount = await calculateSegmentMemberCount(segment.rules);

  logger.info("Segment updated", { category: 'API', segmentId, name: segment.name });

  return successResponse({
    ...segment,
    memberCount });
}

/**
 * DELETE /api/admin/segments/[id]
 * Delete a segment
 */
async function handleDelete(_request: NextRequest,
  context: RouteContext | undefined): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const { id } = await (context as RouteParams).params;
  const segmentId = parseInt(id);

  if (isNaN(segmentId)) {
    throw ApiError.badRequest("Invalid segment ID");
  }

  // Check if segment is used in any promotions
  const promotionCount = await prisma.promotionCustomerSegment.count({
    where: { segmentId } });

  if (promotionCount > 0) {
    throw ApiError.badRequest(
      `Cannot delete segment: it is used in ${promotionCount} promotion(s)`
    );
  }

  await prisma.customerSegment.delete({
    where: { id: segmentId } });

  logger.info("Segment deleted", { category: 'API', segmentId });

  return successResponse({ message: "Segment deleted successfully" });
}

// Helper function to calculate segment member count
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async function calculateSegmentMemberCount(rules: unknown): Promise<number> {
  try {
    // For now, return a count of all users
    // TODO: In a full implementation, this would parse rules and build a dynamic query
    const count = await prisma.user.count();
    return count;
  } catch {
    return 0;
  }
}

// Helper function to get sample members
 
async function getSampleMembers(rules: unknown, limit: number) {
  try {
    const users = await prisma.user.findMany({
      take: limit,
      select: {
        id: true,
        email: true,
        name: true,
        createdAt: true },
      orderBy: { createdAt: "desc" } });

    return users.map((u) => ({
      id: u.id,
      email: u.email,
      name: u.name || "N/A",
      joinedAt: u.createdAt }));
  } catch {
    return [];
  }
}

export const GET = withErrorHandling(withAdmin(handleGet));
export const PUT = withErrorHandling(withAdmin(handlePut));
export const DELETE = withErrorHandling(withAdmin(handleDelete));